<template>
  <div>
    <div class="topSearch">
      <p><span>单名：<el-input size="small" style="width: 250px" v-model="params.purchaseName"
                            placeholder="请输入" clearable></el-input></span></p>
      <p><span>供应商：  <el-select
          v-model="params.supplierId"
          filterable
          size="small"
          clearable
          style="width: 250px">
                  <el-option
                      v-for="(item, index) in supplierList"
                      :label="item.name"
                      :value="item.id"
                      :key="index"
                  ></el-option>
                </el-select></span></p>
      <p><span>仓库：  <el-select
          size="small"
          style="width: 250px"
          v-model="params.areaId"
          clearable
      >
              <el-option
                  v-for="item in warehouseList"
                  :label="item.areaName"
                  :value="item.area"
                  :key="item.area"
              ></el-option> </el-select
      ></span></p>
      <p>
        <el-button size="small" type="primary" @click="_search">查 询</el-button>
      </p>
    </div>
    <el-table :data="tableData"
              border
              height="calc(100vh - 250px)"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              v-loading="loading"
              :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }">
      <el-table-column prop="purchaseId" label="单号" width="80px"/>
      <el-table-column prop="purchaseName" label="单名"/>
      <el-table-column prop="areaName" label="仓库"/>
      <el-table-column prop="factoryName" label="所属工厂" width="120px"></el-table-column>
      <el-table-column label="明细" width="900px">
        <template v-slot:default="scope">
          <el-table
              :data="scope.row.deliverByGoods"
              maxHeight="250px"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
                textAlign: 'center',
                fontWeight: 400,
                background: '#66b1ff',
                color: 'white',
              }"
              border
              style="width: 100%"
          >
            <el-table-column prop="goodName" label="产品" width="150px"/>
            <el-table-column prop="skuCode" label="SKU码"/>
            <el-table-column prop="size" label="规格"/>
            <el-table-column prop="color" label="颜色"/>
            <el-table-column prop="unit" label="单位"/>
            <el-table-column prop="supplierName" label="供应商"/>
            <el-table-column prop="deliverQuantity" label="采购数量"/>
            <el-table-column prop="receiveQuantity" label="收货数量"/>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column>
        <template v-slot:default="scope">
          <div style="margin-bottom: 10px"><p>采购时间：</p>{{ scope.row.deliveryDate || '-' }}</div>
          <div><p>收货时间：</p>{{ scope.row.receiveDate || '-' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template v-slot:default="scope">
          <span v-if="scope.row.status==0" style="color: #dd6161">待入库</span>
          <span v-if="scope.row.status==1" style="color: #67c23a">已入库</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot:default="scope">
          <!--          <el-button size="small" type="primary" style="margin-bottom: 10px" @click="toDelivery(scope.row)">去发货-->
          <!--          </el-button>-->
          <el-button size="small" type="warning" @click="_down(scope.row)" v-if="authority.includes(721)">下载发货单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="padding: 20px 0"
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
    >
    </el-pagination>

    <!--    去发货弹窗-->
    <el-dialog :visible.sync="visibleDialog" center title="发货单" width="60%">
      <el-table
          :data="deliveryData"
          :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
          :headerCellStyle="{
                textAlign: 'center',
                fontWeight: 400,
                background: '#66b1ff',
                color: 'white',
              }"
          border
      >
        <el-table-column prop="goodName" label="产品" width="150px"/>
        <el-table-column prop="skuCode" label="SKU码"/>
        <el-table-column prop="size" label="规格"/>
        <el-table-column prop="color" label="颜色" width="100px"/>
        <el-table-column prop="unit" label="单位" width="100px"/>
        <el-table-column prop="supplierName" label="供应商"/>
        <el-table-column prop="purchaseNum" label="采购数量" width="100px"/>
        <el-table-column prop="receiveQuantity" label="发货数量" width="160px">
          <template v-slot:default="scope">
            <el-input-number v-model="scope.row.deliverQuantity" size="small"></el-input-number>
          </template>
        </el-table-column>

      </el-table>
      <span slot="footer">
          <el-button size="small" @click="visibleDialog=false">取 消</el-button>
          <el-button type="primary" size="small" @click="_comfirm">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import quinn from "../../utils/quinn";

export default {
  name: "deliveryNote",
  data() {
    return {
      tableData: [],
      supplierList: [],
      totalCount: 0,
      currentPage: 1,
      deliveryData: [],
      warehouseList: [],
      authority: [],
      params: {
        purchaseName: "",
        pageSize: 20,
        pageNumber: 1,
        areaId: "",
        supplierName: ""
      },
      loading: false,
      dialogDetial: {},
      visibleDialog: false,
    }
  },
  created() {
    const {authorityList = [],} = quinn.getStorage("userData") || {};
    this.authority = authorityList;
    this.getData()
    this.$api.areaLedgerAreaList().then((res) => {
      this.warehouseList = res
    })
    this.$api.purchaseGetSupplierVo({name: ""}).then((res) => {
      this.supplierList = res;
    });
  },
  methods: {
    getData() {
      this.loading = true
      this.$api.tagByPurchaseDeliverGetTagByPurchaseDeliverList(this.params).then(res => {
        this.tableData = res.records
        this.totalCount = res.total
        this.loading = false
      })
    },
    toDelivery(row) {
      this.visibleDialog = true
      this.dialogDetial = row
      this.$api.purchaseGetPurchaseOrderByDelivery({purchaseId: row.purchaseId}).then(res => {
        res.map(el => this.$set(el, 'deliverQuantity', 0))
        this.deliveryData = res
      })

    },
    _down(row) {
      this.$message.success('正在下载中...')
      axios({
        url: `${this.$apiHost}/tagByPurchaseDeliver/getPaperDeliveryExcel`,
        method: 'get',
        responseType: 'blob',
        headers: {
          token: window.$quinn.getStorage("token")
        },
        params: {
          tagByPurchaseDeliverId: row.id,    // 单号
        }
      }).then(res => {
        const disposition = res.headers['content-disposition'];
        let fileName = row.purchaseName + '-发货单.xlsx'; // 默认给个 .xlsx

        if (disposition) {
          const match = disposition.match(/filename="?([^"]+)"?/);
          if (match) {
            fileName = decodeURIComponent(match[1]);
            // 如果没有后缀，就补 .xlsx
            if (!fileName.includes('.')) {
              fileName += '.xlsx';
            }
          }
        }
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        URL.revokeObjectURL(link.href);
      });

    },
    _comfirm() {
      const deliverByGoods = this.deliveryData.filter((item) => item.deliverQuantity != 0)
      const data = {
        purchaseId: this.dialogDetial.purchaseId,
        purchaseName: this.dialogDetial.purchaseName,
        areaId: this.dialogDetial.areaId,
        deliverByGoods: deliverByGoods,
      }
      this.$api.purchasePurchaseOrderDelivery(data).then(res => {
        if (res == 1) {
          this.$message.success('发货成功！')
          this.visibleDialog = false
        } else {
          this.$message.success('失败，请稍后重试！')
        }
      })
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getData()
    },
    _search() {
      this.params.pageNumber = 1
      this.getData()
    }
  }
}
</script>

<style scoped lang="less">
.topSearch {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  p {
    margin-right: 20px;
  }

  margin-bottom: 10px;
}

</style>